package Utils.Aspect;

import Test.A;
import Test.B;
import Utils.LoadClassBean;
import annotation.Aspect;
import annotation.Before;
import component.Ioc;

import java.io.File;
import java.lang.reflect.Method;

public class AspectUtils {
    private static void dealDir(String filepath) throws ReflectiveOperationException {
        File file = new File(AspectUtils.class.getResource(filepath).getPath());
        String[] names = file.list();
        for(String str : names){
            str = filepath+str;
            file = new File(LoadClassBean.class.getResource(str).getPath());
            if(file.isDirectory()){
                dealDir(str+"/");
            }else{
                if(str.endsWith(".class")){
                    str = str.substring(1,str.length()-6).replaceAll("/",".");
                    dealClass(str);
                }
            }
        }
    }
    private static void dealClass(String str) throws ClassNotFoundException, NoSuchMethodException {
        Class<?> klass = Class.forName(str);
        if (klass.getDeclaredAnnotation(Aspect.class) == null) return;
        Method[] methods = klass.getMethods();
        for (Method method : methods){
            if (method.getDeclaredAnnotation(Before.class)!=null){
                String filepath = method.getDeclaredAnnotation(Before.class).value();
                AspectFactory.solve(filepath, klass, method);
            }
        }
    }

    public static void main(String[] args) {
        try {
            dealDir("/");
            A hello =  (A)Ioc.getBean("A");
            hello.test();
            B world =  (B) Ioc.getBean("B");
        } catch (ReflectiveOperationException e) {
            e.printStackTrace();
        }
    }
}
